using Microsoft.Win32;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// 创建文件夹对话框
    /// </summary>
    public partial class CreateFolderDialog : Window
    {
        public string FolderName => FolderNameTextBox.Text.Trim();
        public string SelectedPath { get; private set; } = string.Empty;
        public string DefaultPath { get; set; } = string.Empty;

        public CreateFolderDialog()
        {
            InitializeComponent();
            Loaded += CreateFolderDialog_Loaded;
        }

        private void CreateFolderDialog_Loaded(object sender, RoutedEventArgs e)
        {
            // 设置默认路径
            if (!string.IsNullOrEmpty(DefaultPath) && Directory.Exists(DefaultPath))
            {
                SelectedPath = DefaultPath;
                CurrentPathTextBlock.Text = DefaultPath;
                LoadFolderTree(DefaultPath);
            }
            else
            {
                // 默认使用文档文件夹
                var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                SelectedPath = documentsPath;
                CurrentPathTextBlock.Text = documentsPath;
                LoadFolderTree(documentsPath);
            }

            // 聚焦到文件夹名称输入框
            FolderNameTextBox.Focus();
            FolderNameTextBox.SelectAll();
        }

        private void LoadFolderTree(string rootPath)
        {
            try
            {
                FolderTreeView.Items.Clear();

                if (!Directory.Exists(rootPath))
                    return;

                var rootItem = new FolderItem
                {
                    Name = Path.GetFileName(rootPath) ?? rootPath,
                    FullPath = rootPath
                };

                LoadSubFolders(rootItem);
                FolderTreeView.Items.Add(rootItem);

                // 展开根节点
                if (FolderTreeView.Items.Count > 0)
                {
                    var container = FolderTreeView.ItemContainerGenerator.ContainerFromItem(rootItem) as System.Windows.Controls.TreeViewItem;
                    if (container != null)
                    {
                        container.IsExpanded = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载文件夹树失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void LoadSubFolders(FolderItem parentItem)
        {
            try
            {
                var directories = Directory.GetDirectories(parentItem.FullPath)
                    .Where(dir => !Path.GetFileName(dir).StartsWith(".")) // 排除隐藏文件夹
                    .OrderBy(dir => Path.GetFileName(dir))
                    .Take(50); // 限制数量避免性能问题

                foreach (var directory in directories)
                {
                    var folderItem = new FolderItem
                    {
                        Name = Path.GetFileName(directory),
                        FullPath = directory
                    };

                    // 检查是否有子文件夹，如果有则添加占位符
                    try
                    {
                        if (Directory.GetDirectories(directory).Any())
                        {
                            folderItem.Children.Add(new FolderItem { Name = "加载中..." });
                        }
                    }
                    catch
                    {
                        // 忽略权限错误
                    }

                    parentItem.Children.Add(folderItem);
                }
            }
            catch
            {
                // 忽略权限错误
            }
        }

        private void FolderTreeView_SelectedItemChanged(object sender, System.Windows.RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue is FolderItem selectedItem)
            {
                SelectedPath = selectedItem.FullPath;
                CurrentPathTextBlock.Text = selectedItem.FullPath;

                // 延迟加载子文件夹
                if (selectedItem.Children.Count == 1 && selectedItem.Children[0].Name == "加载中...")
                {
                    selectedItem.Children.Clear();
                    LoadSubFolders(selectedItem);
                }
            }
        }

        private void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            var saveFileDialog = new Microsoft.Win32.SaveFileDialog
            {
                Title = "选择文件夹创建位置",
                FileName = "选择文件夹",
                DefaultExt = "",
                Filter = "文件夹|*."
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                var selectedPath = Path.GetDirectoryName(saveFileDialog.FileName);
                if (!string.IsNullOrEmpty(selectedPath))
                {
                    SelectedPath = selectedPath;
                    CurrentPathTextBlock.Text = selectedPath;
                    LoadFolderTree(selectedPath);
                }
            }
        }

        private void Create_Click(object sender, RoutedEventArgs e)
        {
            // 验证输入
            if (string.IsNullOrWhiteSpace(FolderName))
            {
                MessageBox.Show("请输入文件夹名称", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                FolderNameTextBox.Focus();
                return;
            }

            if (string.IsNullOrEmpty(SelectedPath) || !Directory.Exists(SelectedPath))
            {
                MessageBox.Show("请选择有效的创建路径", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // 检查文件夹名称是否包含非法字符
            var invalidChars = Path.GetInvalidFileNameChars();
            if (FolderName.Any(c => invalidChars.Contains(c)))
            {
                MessageBox.Show("文件夹名称包含非法字符，请重新输入", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                FolderNameTextBox.Focus();
                return;
            }

            DialogResult = true;
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }
    }
}
